from typing import Tuple

from src.core.response_handler import ResponseHandler
from src.core.query_handler import QueryHandler
from src.model.message.messages import DHTMessage

class MessageDispatcher:
    """消息分发器"""
    
    def __init__(self, response_handler: ResponseHandler, query_handler: QueryHandler):
        self.response_handler = response_handler
        self.query_handler = query_handler

    def dispatch(self, data: bytes, addr: Tuple[str, int]):
        """分发消息到对应的处理器"""
        try:
            message = DHTMessage.from_bytes(data)
            
            if message.message_type == 'r':
                self.response_handler.handle_response(data, addr)
            elif message.message_type == 'q':
                self.query_handler.handle_query(data, addr)
                
        except Exception as e:
            self.logger.error(f"消息分发失败: {e}", exc_info=True) 